<?php
function NewDB($dbHost, $dbName, $dbUser, $dbPass) {
	$db = new DB_Sql();
	$db->Database = "$dbName";
	$db->User     = "$dbUser";
	$db->Password = "$dbPass";
	$db->Host     = "$dbHost";

	return $db;
}
function QueryString() {
	global $REDIRECT_QUERY_STRING, $HTTP_SERVER_VARS, $QUERY_STRING;
	$queryString = $REDIRECT_QUERY_STRING;
	if (!isset($queryString) || $queryString=="") $queryString = $HTTP_SERVER_VARS["REDIRECT_QUERY_STRING"];
	if (!isset($queryString) || $queryString=="") $queryString = $QUERY_STRING;
	return $queryString;
}

function InDir($dir, $path) {
	if (strpos(strtolower($path), strtolower($dir))===false) return false;
	return true;
}
function IsIE() {
	return IE=="true";
}

function ToHTML($strValue)
{
  return htmlspecialchars($strValue);
}
// ----------------------------------------------------------------------------------------------
function ToURL($strValue)
{
  return urlencode($strValue);
}
// ----------------------------------------------------------------------------------------------
function GetParam($ParamName)
{
  global $_POST;
  global $_GET;

  $ParamValue = "";
  if(isset($_POST[$ParamName]))
    $ParamValue = $_POST[$ParamName];
  else if(isset($_GET[$ParamName]))
    $ParamValue = $_GET[$ParamName];

  return $ParamValue;
}
// ----------------------------------------------------------------------------------------------
function IsNumner($string_value)
{
  if(is_numeric($string_value) || !strlen($string_value))
    return true;
  else 
    return false;
}
//-------------------------------------------------------------------------------------------
function ToSQLPostVAL($value)
{
	if (is_null($value))
		return "NULL";

   // Stripslashes
   if (get_magic_quotes_gpc()) {
	   $value = stripslashes($value);
   }
   // Quote if not a number or a numeric string
   $value = "'" . mysql_escape_string($value) . "'";
   
   return $value;
}
function ToSQLNormalVAL($value)
{
     return  "'" . mysql_escape_string($value) . "'";
}
// ----------------------------------------------------------------------------------------------
function Strip($value)
{
  if(get_magic_quotes_gpc() == 0)
    return $value;
  else
    return stripslashes($value);
}
// ----------------------------------------------------------------------------------------------
function IsEmail($address) {
    if( ereg( ".*<(.+)>", $address, $regs ) ) {
        $address = $regs[1];
    }
    if(ereg( "^[^@  ]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{1,})\$",$address) )
        return true;
    else
        return false;
}
// ----------------------------------------------------------------------------------------------
function ChkNumber($strNumber) {
	$strNumber = trim($strNumber);
	if (strlen($strNumber) == 1 && !isNumber($strNumber)) return "not a number";
	if (substr($strNumber, 0, 1)=="-" || substr($strNumber, 0, 1)=="+") $strNumber = substr($strNumber, 1);
	$comma = 0;
	for ($i=0; $i<=strlen($strNumber); $i++) {
		$pt = substr($strNumber, $i, 1);
		if (!isNumber($pt) && $pt!=".") return "not a number";
		else if($pt==".") $comma++;
	}
	if ($comma>=2) return "not a number";
	return "";
}
// ----------------------------------------------------------------------------------------------------------
function CheckDateMMDDYY($strdate, $split) {
	$msgErr = "Invalid date! Enter the date in 'mm/dd/yyyy' format!";
	if((substr_count($strdate,$split))<>2){
		return $msgErr;
	}
	
	$pos = strpos($strdate,"/");
	$month = substr($strdate,0,($pos));
	$date= substr($strdate,($pos+1),($pos));
	$result=ereg("^[0-9]+$",$date,$trashed);
	if(!($result))
		return $msgErr;
	$year= substr($strdate,($pos+4),strlen($strdate));

	if(!checkdate($month, $date, $year)) {
		return $msgErr;
	}
	return "";
}

function CheckDateDDMMYY($strdate, $split) {
	$msgErr = "Invalid date! Enter the date in 'mm/dd/yyyy' format!";
	if((substr_count($strdate,$split))<>2){
		return $msgErr;
	}
	
	$pos = strpos($strdate,"/");
	$month = substr($strdate,0,($pos));
	$date= substr($strdate,($pos+1),($pos));
	$result=ereg("^[0-9]+$",$date,$trashed);
	if(!($result))
		return $msgErr;
	$year= substr($strdate,($pos+4),strlen($strdate));

	if(!checkdate($month, $date, $year)) {
		return $msgErr;
	}
	return "";
}

function GetIDSeed() {
	global $UserID;
	return $UserID."-".implode("", gettimeofday());
	//return "";
}


function FormatNumeric($value, $isDecimal) {
	$retValue = "";
	if ($isDecimal) {
		$retValue = sprintf("%01.2f", $value);
	} else {
		$retValue = sprintf("%d", $value);
	}
	$thapphan = substr($retValue, strlen($retValue)-3);
	$nguyen	  = substr($retValue, 0, strlen($retValue)-3);
	$du = strlen($nguyen)%3;
	if ($du!=0)
		$nguyen = str_repeat("0", 3-$du).$nguyen;
	if (strlen($nguyen)>3)
		$nguyen = wordwrap($nguyen, 3, ",", 1);
	if ($du!=0)
		$nguyen = substr($nguyen, 3-$du);
	//echo "<!-- ||$nguyen$thapphan || -->";
	//exit;
	$retValue = str_replace(",.", ".", $nguyen.$thapphan);
	return $retValue;
	
}
function FormatDateSQL($value) {
	$date = explode("/", $value);
	if ($value=="" || count($date)<3) return "0000-00-00 00:00:00";
	$retValue = sprintf("%04d", $date[2])."-".sprintf("%02d", $date[1])."-".sprintf("%02d", $date[0])." 00:00:00";
	return $retValue;
}
function DateDDMMYYY($value, $sep="/") {
	if ($value!="") {
		$retValue = substr($value, 8, 2).$sep.substr($value, 5, 2).$sep.substr($value, 0, 4);
		if ($retValue!="00$sep00$sep0000")
			return $retValue;
	}
	return "";
}
function DateMMDDYYY($value, $sep="/") {
	if ($value!="") {
		$retValue = substr($value, 5, 2).$sep.substr($value, 8, 2).$sep.substr($value, 0, 4);
		if ($retValue!="00$sep00$sep0000")
			return $retValue;
	}
	return "";
}
function VNSupplierShowDate($value, $hastime=false)
{
	$months = array("01"=>"Jan", "02"=>"Feb", "03"=>"Mar", "04"=>"Apr", "05"=>"May", "06"=>"Jun", 
						"07"=>"Jul", "08"=>"Aug", "09"=>"Sep", "10"=>"Oct", "11"=>"Now", "12"=>"Dec");
	if ($value!="" && $value!="0000-00-00 00:00:00") {
		$day = substr($value, 8, 2);
		$month = substr($value, 5, 2);
		$year = substr($value, 0, 4);
		$time = substr($value, 10);
		
		return $day."-".$months[$month]."-".$year.($hastime?$time:"");
	}
	return "";
}
function VNSupplierDateToMysql($value)
{
	if ($value== "00-00-0000 00:00:00" || $value== "")
			$value = "0000-00-00 00:00:00";
		else	
			$value	=   date( 'Y-m-d H:i:s', strtotime($value));
	return $value;
}
function GetStartNameofPic($dir, &$startName, $len) {
	if (is_dir($dir)) {
	   if ($dh = opendir($dir)) {
	   	   $lastName = "000.gif";
		   while (($file = readdir($dh)) !== false) {
			   if ($file != "." && $file != "..") {
			   		$lastName = $file;
			   }
		   }
		   $startName = substr($lastName, 0, $len);
		   $start = (int)$startName+1;
		   $startName = sprintf("%03d", $start);
		   //echo $startName;
		   closedir($dh);
	   }
	}
}
function ShowObject($obj, $comment="") {
	echo "$comment:<pre>";
	print_r($obj);
	echo "</pre>";
}
function ListIDs($db, $table, $where="1=1")
{
	$listIDs = "";
	$query = "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ListIDs FROM $table WHERE $where";
	if ($db->query($query)) {
		while ($db->next_record()) 	{
			$listIDs = $db->f("ListIDs");
		}
	}
	return $listIDs;
}

function GeneratePartnerCode($db, $provinceid, $where="")
{
	$maxCode = "00000";
	$province = provinceDAL::Load($db, $provinceid, $pageError);
	$query = "SELECT MAX(SUBSTR(partnercode, 3, 5)) AS MaxCode FROM partner ".($where!=""?" WHERE $where":"");
	if ($db->query($query)) {
		while ($db->next_record()) 	{
			$maxCode = $db->f("MaxCode");
		}
	}
	$max = (int)$maxCode + 1;
	
	return sprintf("PA%05d".$province->provincecode, $max);
}

function GenerateCateCode($db)
{
	$maxCode = "00000";
	$query = "SELECT MAX(SUBSTR(catecode, 2, 5)) AS MaxCode FROM categories WHERE CHAR_LENGTH(catecode)=6";
	if ($db->query($query)) {
		while ($db->next_record()) 	{
			$maxCode = $db->f("MaxCode");
		}
	}
	$max = (int)$maxCode + 1;
	
	return sprintf("C%05d", $max);
}

function GenerateSubCateCode($db)
{
	$maxCode = "00000";
	$query = "SELECT MAX(SUBSTR(catechildcode, 3, 5)) AS MaxCode FROM categorieschild WHERE CHAR_LENGTH(catechildcode)=7";
	if ($db->query($query)) {
		while ($db->next_record()) 	{
			$maxCode = $db->f("MaxCode");
		}
	}
	$max = (int)$maxCode + 1;
	
	return sprintf("SC%05d", $max);
}

function GenerateProductCode($db)
{
	$maxCode = "00000";
	$query = "SELECT MAX(SUBSTR(procode, 2, 5)) AS MaxCode FROM products WHERE CHAR_LENGTH(procode)=6";
	if ($db->query($query)) {
		while ($db->next_record()) 	{
			$maxCode = $db->f("MaxCode");
		}
	}
	$max = (int)$maxCode + 1;
	
	return sprintf("S%05d", $max);
}

function genRandomString($length) {
    //$length = 6;
    $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
    $string = "";    

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string;
}

function GetComboBox($db, $tableName, $whereStr, $orderByStr, $optName, $fieldValue, $fieldText, $firstText, $firstValue, &$defaultVAL, $extraAttr, $moreAtt) {	
	$errorMsg = $returnData = "";	
	$query	= "SELECT * FROM $tableName";		
	
	if ((!isset($defaultVAL) || $defaultVAL=="") && $i==0) {
		$defaultVAL = $firstValue;
		$returnData .= "\t<OPTION VALUE='$firstValue' SELECTED>$firstText</OPTION>\r";		
	} else $returnData .= "\t<OPTION VALUE='$firstValue'>$firstText</OPTION>\r";		

	if ($whereStr!="") $query = $query." WHERE ".$whereStr;
	if ($orderByStr!="") $query = $query." ORDER BY ".$orderByStr;
	if ($limit!="") $query = $query." LIMIT ".$limit;

	if (!$db->query($query)) {		
		$errorMsg	= mysql_error()." Query: $query.";		
	} else {		
		while ($db->next_record()) 	{
			$value		= $db->f($fieldValue);		
			$display	= $db->f($fieldText);			
			if ((!isset($defaultVAL) || $defaultVAL=="") && $i==0) $defaultVAL = $value;
			if ($value == $defaultVAL)				
				$returnData .= "\t<OPTION VALUE='$value' SELECTED>$display</OPTION>\r";			
			else				
				$returnData .= "\t<OPTION VALUE='$value'>$display</OPTION>\r";		
		}
	}	

	if ($returnData!="") $returnData = "\r<SELECT NAME='$optName' $extraAttr $moreAtt>\r$returnData</SELECT>\r";		
	
	return $returnData;	
}

function GetNewComboBox($db, $tableName, $whereStr, $orderByStr, $optName, $fieldValue, $fieldText, $firstText, $firstValue, &$defaultVAL, $extraAttr, $moreAtt) {	
	$errorMsg = $returnData = "";	
	$query	= "SELECT * FROM $tableName";		
	
	if($firstText !== "") {
		$returnData .= "\t<OPTION VALUE='$firstValue' SELECTED>$firstText</OPTION>\r";	
	}

	if ($whereStr!="") $query = $query." WHERE ".$whereStr;
	if ($orderByStr!="") $query = $query." ORDER BY ".$orderByStr;
	if ($limit!="") $query = $query." LIMIT ".$limit;

	if (!$db->query($query)) {		
		$errorMsg	= mysql_error()." Query: $query.";		
	} else {		
		while ($db->next_record()) 	{
			$value		= $db->f($fieldValue);		
			$display	= $db->f($fieldText);						
			$returnData .= "\t<OPTION VALUE='$value'>$display</OPTION>\r";		
		}
	}	

	if ($returnData!="") $returnData = "\r<SELECT NAME='$optName' $extraAttr $moreAtt>\r$returnData</SELECT>\r";		
	
	return $returnData;	
}


function GetComboBoxFromVars($arrValues, $optName, $firstText, $firstValue, &$defaultVAL, $extraAttr) {
	$returnData = "";	
	
	if ($firstValue!="")			
		$returnData .= "\t<OPTION VALUE='$firstValue'>$firstText</OPTION>\r";	
	$i = 0 ;
	while (list($value, $display) = each($arrValues)) 	{
		if ((!isset($defaultVAL) || $defaultVAL=="") && $i==0) $defaultVAL = $value;
		if ($value == $defaultVAL)				
			$returnData .= "\t<OPTION VALUE='$value' SELECTED>$display</OPTION>\r";			
		else				
			$returnData .= "\t<OPTION VALUE='$value'>$display</OPTION>\r";		
		$i++;
	}
	if ($returnData!="") $returnData = "\r<SELECT NAME='$optName' $extraAttr>\r$returnData</SELECT>\r";		
	return $returnData;
}

function GetComboBoxByQuery($db, $query, $optName, $fieldValue, $fieldText, $firstText, $firstValue, &$defaultVAL, $extraAttr, $moreAtt) {	
	$errorMsg = $returnData = "";	
	
	if ((!isset($defaultVAL) || $defaultVAL=="") && $i==0) {
		$defaultVAL = $firstValue;
		$returnData .= "\t<OPTION VALUE='$firstValue' SELECTED>$firstText</OPTION>\r";		
	} else $returnData .= "\t<OPTION VALUE='$firstValue'>$firstText</OPTION>\r";		

	if (!$db->query($query)) {		
		$errorMsg	= mysql_error()." Query: $query.";		
	} else {		
		while ($db->next_record()) 	{
			$value		= $db->f($fieldValue);		
			$display	= $db->f($fieldText);			
			if ((!isset($defaultVAL) || $defaultVAL=="") && $i==0) $defaultVAL = $value;
			if ($value == $defaultVAL)				
				$returnData .= "\t<OPTION VALUE='$value' SELECTED>$display</OPTION>\r";			
			else				
				$returnData .= "\t<OPTION VALUE='$value'>$display</OPTION>\r";		
		}
	}	

	if ($returnData!="") $returnData = "\r<SELECT NAME='$optName' $extraAttr $moreAtt>\r$returnData</SELECT>\r";		
	
	return $returnData;	
}

?>